package com.tanhua.admin.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.service.AdminService;
import com.tanhua.commons.utils.Constants;
import com.tanhua.model.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/system/users")
public class SystemController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 接口名称：用户登录验证码图片
     * 接口路径：GET/system/users/verification
     */
    @GetMapping("/verification")
    public void verification(String uuid, HttpServletResponse response) throws IOException {
        //1. 通知浏览器不要缓存
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        //2. 生成验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(299, 97);
        //3.把验证码存储到redis中
        String code = lineCaptcha.getCode(); //验证码里面内容
        redisTemplate.opsForValue().set(Constants.CAP_CODE+uuid,code,5, TimeUnit.MINUTES);

        //4. 输出验证码图片即可
        lineCaptcha.write(response.getOutputStream());
    }

    /**
     *接口名称：用户登录
     *接口路径：POST/system/users/login
     *
     */
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map<String,String> paramMap) throws IOException {
        Map<String,String> resultMap = adminService.login(paramMap);
        return ResponseEntity.ok(resultMap);
    }

    /**
     *接口名称：用户基本信息
     *接口路径：POST/system/users/profile
     */
    @PostMapping("/profile")
    public ResponseEntity profile() throws IOException {
        AdminVo adminVo = adminService.profile();
        return ResponseEntity.ok(adminVo);
    }

}
